package com.biwano.swapmyjob.mail;

import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ejb.Singleton;
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;

import com.biwano.swapmyjob.tools.Config;


@Singleton
public class MailConnectionManager {

	private Session mailSession;
	private ExecutorService mailersPool;

	@PostConstruct
	public void connect() {

		Properties props = new Properties();
		props.put("mail.transport.protocol", Config.get("mail_transport_protocol"));
		props.put("mail.smtp.starttls.enable", Config.get("mail_smtp_starttls_enable"));
		props.put("mail.smtp.host", Config.get("mail_smtp_host"));
		props.put("mail.smtp.port", Config.get("mail_smtp_port"));
		props.put("mail.smtp.auth", Config.get("mail_smtp_auth"));

		
		Authenticator auth = new SMTPAuthenticator();

		mailSession = Session.getInstance(props, auth);
		
		mailersPool = Executors.newCachedThreadPool();
	
	}

	public void send(String recipient, String subject, String text) {
		
	try {
			Message message = new MimeMessage(mailSession);

			InternetAddress fromAddress = new InternetAddress(Config.get("mail_message_sender"));
			InternetAddress toAddress = new InternetAddress(recipient);

			message.setFrom(fromAddress);
			message.setRecipient(RecipientType.TO, toAddress);
			message.setSubject(subject);
			message.setContent(text, "text/html");

			mailersPool.execute(new MailerThread(message));

		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	@PreDestroy
	public void disconnect() {
	}

	private class SMTPAuthenticator extends javax.mail.Authenticator {
		public PasswordAuthentication getPasswordAuthentication() {
			return new PasswordAuthentication(Config.get("mail_smtp_auth_user"), 
					Config.get("mail_smtp_auth_password"));
		}
	}

	private class MailerThread implements Runnable {
		Message message;

		public MailerThread(Message message) {
			this.message = message;
		}

		public void run() {
			try {
				Transport.send(message);
			} catch (MessagingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}
